package com.yc.thread.wait;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized 可以配合 object.wait()/ object.notify()实现线程之间的交互
 * lock也有一套类似的实现机制
 * 参考https://www.cnblogs.com/cyl048/p/10882013.html
 * @author yuancan
 *
 */
public class TestWait4 {
	
	volatile boolean isProcess = false;
	
	public void m() {
		Lock lock = new ReentrantLock();
		Condition condition = lock.newCondition();
		
		/**
		 * 1. wait
		 * 2. sleep 20秒
		 * 
		 */
		new Thread(() -> {
			System.out.println("-------T1------");
			lock.lock();
			isProcess = true;
			
			//释放锁
			try {
				condition.await();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println("--T1---over");
			
		},"T1").start();
		
//		System.out.println("-------T2----a--");
//		try {
//			condition.await();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		condition.signalAll();//在同步块外使用报错java.lang.IllegalMonitorStateException
//		System.out.println("--T2--a-over");
		
//		new Thread(() -> {
//			lock.lock();
//			System.out.println("-------T2------");
//			condition.signal();
//			condition.signalAll();
//			System.out.println("--T2---over");
//			lock.unlock();
//		},"T2").start();
		
	}

	public static void main(String[] args) {
		TestWait4 tw = new TestWait4();
		tw.m();

	}

}
